package net.src.tcp_sms;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Scanner;

/**
 * 通过客户端和服务器实现群聊即时通信
 */
public class ClientDemo2 {
    public static void main(String[] args) throws Exception {
        System.out.println("启动客户端成功!");
        //连接与服务器的socket
        Socket socket = new Socket(InetAddress.getLocalHost(),8888);

        //创建一个专门的线程专门负责这个客户端的读消息
        new ClientReaderThread(socket).start();

        //从socket通信管道中获取字节输出流,发送数据
        OutputStream os = socket.getOutputStream();
        //把它包装成高级的打印流
        PrintStream ps = new PrintStream(os);

        Scanner sc = new Scanner(System.in);
        while(true){
            //发送消息
            System.out.print("请说:");
            ps.println(sc.nextLine());
            ps.flush();//发完要刷新,不然在缓冲区
        }


        //tcp通信不要轻易的关闭管道,等关机或者用户主动关闭
    }
}

class ClientReaderThread extends Thread{
    private Socket socket;
    public ClientReaderThread(Socket socket){
        this.socket = socket;
    }
    @Override
    public void run() {
        try {
            //socket获取字节流,字节流包装成字符流,再包装成字符缓冲流
            BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String msg;
            while((msg = br.readLine())!=null){
                System.out.println(socket.getRemoteSocketAddress() + ":" + msg);
            }
        } catch (Exception e) {
            System.out.println("被服务端强制下线!");
        }
    }
}